﻿using DeHeng_Mes.Dao;
using DeHeng_Mes.Utils;
using NPOI.SS.Formula.Functions;
using S7.Net;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using MappingTable = DeHeng_Mes.Utils.MappingTable;

namespace DeHeng_Mes.PlcService
{
    public class ErrorType
    {
        #region 成员实例
        OrderDao orderDao = new OrderDao();
        #endregion

        /// <summary>
        /// 工序增补
        /// </summary>
        /// <param name="station"></param>
        /// <param name="codes"></param>
        /// <returns></returns>
        public byte InsertStation(string station, string code, Model.ConfigModel.PlcOrderConfigModel orderModel)
        {
            try
            {
                // 获取Plc信号数组
                Tuple<int, int> byteTuple = MappingTable.GetBytesOff(orderModel.PlcName + "-STATUS");

                byte[] bytes1 = orderModel.plc.ReadBytes(DataType.DataBlock, 5001, 0, byteTuple.Item2);

                List<int> errorLists = new List<int>();

                for (int i = 0; i <= 4; i++)
                {
                    int nowIndex = i * 2 + (index * 50 + 4);

                    errorLists.Add(S7.Net.Types.Int.FromByteArray(bytes1.Skip(nowIndex).Take(2).ToArray()));
                }

                Dictionary<int, string> dictionary = MappingTable.GetLastStation(station);

                string lastStation = string.Empty;

                string code = string.Empty;

                foreach (int errorCode in errorLists)
                {
                    if(errorCode == 1120)
                    {
                        lastStation = dictionary[1];

                        code = codes[0];

                        break;
                    }else if (errorCode == 1121)
                    {
                        lastStation = dictionary[2];

                        code = codes[1];

                        break;
                    }
                }

                if (string.IsNullOrEmpty(lastStation))
                    return (2, new List<int>()
                    {
                        1509
                    });

                if (string.IsNullOrEmpty(code))
                    return (2, new List<int>()
                    {
                        1511
                    });

                List<Model.Table.PartProcess> partProcesses = orderDao.GetProcessDataByTraceIdAndStation(code, lastStation);

                if (partProcesses.Count > 0)
                {
                    return (2, new List<int>()
                    {
                        1510
                    });
                }

                bool isSave = orderDao.LastStationDataIsSave(lastStation, code);

                if (isSave)
                {
                    Tools.ProduceLogText($"[{station}]执行补序任务成功,点检码[{code}]");

                    return (1, new List<int>());
                }
                else
                    return (2, new List<int>()
                    {
                        1513
                    });
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"[{station}]执行补序任务失败，原因是{ex.Message}");

                return (2, new List<int>()
                {
                    1513
                });
            }
        }

        /// <summary>
        /// 结束时间增补
        /// </summary>
        /// <param name="station"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        internal byte InsertEndStation(string station, string code, Model.ConfigModel.PlcOrderConfigModel orderModel)
        {
            try
            {
                // 获取Plc信号数组
                Tuple<int, int> byteTuple = MappingTable.GetBytesOff(orderModel.PlcName + "-STATUS");

                byte[] bytes1 = orderModel.plc.ReadBytes(DataType.DataBlock, 5001, 0, byteTuple.Item2);

                List<int> errorLists = new List<int>();

                for (int i = 0; i <= 4; i++)
                {
                    int nowIndex = i * 2 + (index * 50 + 4);

                    errorLists.Add(S7.Net.Types.Int.FromByteArray(bytes1.Skip(nowIndex).Take(2).ToArray()));
                }

                Dictionary<int, string> dictionary = MappingTable.GetLastStation(station);

                string lastStation = string.Empty;

                string code = string.Empty;

                foreach (int errorCode in errorLists)
                {
                    if (errorCode == 1130)
                    {
                        lastStation = dictionary[1];

                        code = codes[0];

                        break;
                    }
                    else if (errorCode == 1131)
                    {
                        lastStation = dictionary[2];

                        code = codes[1];

                        break;
                    }
                }

                if (string.IsNullOrEmpty(lastStation))
                    return (2, new List<int>()
                    {
                        1514
                    });

                if (string.IsNullOrEmpty(code))
                    return (2, new List<int>()
                    {
                        1515
                    });

                List<Model.Table.PartProcess> partProcesses = orderDao.GetProcessDataByTraceIdAndStation(code, lastStation);

                Model.Table.PartProcess partProcess = partProcesses.OrderByDescending(x => x.Id).FirstOrDefault();

                bool isUpDate = orderDao.UpDateLastStationEndTimeById(partProcess.Id, code);

                if (isUpDate)
                {
                    Tools.ProduceLogText($"[{station}]执行结束时间增补任务成功,点检码[{code}]");

                    return (1, new List<int>());
                }
                else
                    return (2, new List<int>()
                    {
                        1516
                    });
            }
            catch (Exception ex)
            {
                Tools.ProduceLogTextError($"[{station}]执行结束时间增补任务失败，原因是{ex.Message}");

                return (2, new List<int>()
                {
                    1516
                });
            }
        }
    }
}
